/**
 * 场景管理
 */
class SceneManager {
  init() {
    this.bindEvent();
  }

  dispose() {
    this.unBindEvent();
  }

  bindEvent() {
    window.addEventListener('keyup', this.onKeyEvent);
  }

  unBindEvent() {
    window.removeEventListener('keyup', this.onKeyEvent);
  }

  onKeyEvent = (e: KeyboardEvent) => {
    e.preventDefault();
    if (e.key === 'Delete' && !e.ctrlKey && !e.shiftKey && !e.shiftKey) {
      this.handleDelete();
      return;
    }
    if (e.key === 'c' && e.ctrlKey && !e.shiftKey && !e.shiftKey) {
      this.handleCopy();
    }
  };

  handleDelete() {
    if (!window.behaviorDesigner) {
      return;
    }
    const { behaviorDesigner } = window;
    const { nodes, edges } = behaviorDesigner.getSelectElements();

    nodes.forEach((node) => {
      behaviorDesigner.deleteNode(node.id!);
    });

    edges.forEach((edge) => {
      behaviorDesigner.deleteEdge(edge.id!);
    });
  }

  handleCopy() {
    if (!window.behaviorDesigner) {
      return;
    }
    const { behaviorDesigner } = window;
    const { nodes } = behaviorDesigner.getSelectElements();
    if (!nodes.length) {
      return;
    }
    const { type, x, y } = nodes[0];
    const newNodeConfig = {
      type,
      x: x + 20,
      y: y + 20,
    };
    behaviorDesigner.addNode(newNodeConfig);
    behaviorDesigner.clearSelectElements();
  }
}

export default new SceneManager();
